package org.example.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * http请求工具类
 *
 */
@Slf4j
public class HttpUtil {

	private static HttpClient client = HttpClients.createDefault();

	/**
	 * 执行Get请求方法
	 *
	 * @param uri
	 * @return
	 */
	public static JSONObject doGet(String uri) {

		String result;
		HttpGet get = new HttpGet(uri);

		try {
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			log.error("http doGet error : ", e);
			return null;
		}

		if (StringUtils.isNotBlank(result)) {
			return JSONObject.parseObject(result);
		} else {
			return null;
		}
	}

	/**
	 * 执行Get请求方法
	 * 返回string类型
	 *
	 * @param uri
	 * @return
	 */
	public static String doGetReturnStr(String uri) {
		if(StringUtils.isEmpty(uri)){
			return null;
		}
		String result;
		HttpGet get = new HttpGet(uri);

		try {
			HttpResponse response = client.execute(get);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			log.error("http doGet error : ", e);
			return null;
		}

		if (StringUtils.isNotBlank(result)) {
			return result;
		} else {
			return null;
		}
	}

	/**
	 * 执行Post请求方法
	 *
	 * @param uri
	 * @return
	 */
	public static JSONObject doPost(String uri) {

		String result;
		HttpPost post = new HttpPost(uri);

		try {
			List<BasicNameValuePair> parameters = new ArrayList<>();
			parameters.add(new BasicNameValuePair("keyfrom", "wjy-test"));
			parameters.add(new BasicNameValuePair("key", "36384249"));
			parameters.add(new BasicNameValuePair("type", "data"));
			parameters.add(new BasicNameValuePair("doctype", "xml"));
			parameters.add(new BasicNameValuePair("version", "1.1"));
			parameters.add(new BasicNameValuePair("q", "welcome"));
			post.setEntity(new UrlEncodedFormEntity(parameters));
			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			log.error("http doPost error : ", e);
			return null;
		}

		if (StringUtils.isNotBlank(result)) {
			return JSONObject.parseObject(result);
		} else {
			return null;
		}
	}

	public static void main(String[] args) {
		System.out.println(doGet("http://niche.citydo.com.cn/getUserInfo.ashx?userid=18255146362012291315"));
	}
}
